package com.lagou.curator;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.data.Stat;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ServerRegist
 * @Description: 服务注册到Zookeeper
 * @Author: qjc
 * @Date: 2021/9/27 4:18 下午
 */
public class ServerRegistryCenter {

    private ZkClient zkClient;

    public static final String RPC_ROOT = "/rpc-provider";
    public static final String RPC_SPLIT = "/";
    public static final String RPC_COLON = ":";
    public static final String NODE_PREFIX = "server";

    /**
     * 连接zookeeper
     */
    public ServerRegistryCenter() {
        zkClient = new ZkClient("127.0.0.1:2181");
        boolean exists = zkClient.exists(RPC_ROOT);
        if (!exists) {
            zkClient.createPersistent(RPC_ROOT);
        }
    }

    /**
     * 注册到zookeeper
     *
     * @param serverNodePath：服务器接待名称
     * @param ip：ip
     * @param port：端口
     * @return
     * @author qjc
     * @date 2021/9/27 5:04 下午
     */
    public void register(String serverNodePath, String ip, int port) {

        String childPath = RPC_ROOT + RPC_SPLIT + serverNodePath;
        // 0 代表可用，空代表不可用
        String data = ip + RPC_COLON + port + RPC_COLON + "0";
        boolean exists = zkClient.exists(childPath);
        if (!exists) {
            zkClient.createEphemeral(childPath, data);
        }


    }

    /**
     * 获取节点下的子节点列表
     *
     * @param
     * @return
     * @author qjc
     * @date 2021/9/27 5:28 下午
     */
    public List<String> getChildren(String rpcRoot) {
        List<String> children = zkClient.getChildren(rpcRoot);
        return children;
    }

    /**
     * 注册监听
     *
     * @param
     * @return
     * @author qjc
     * @date 2021/9/27 5:34 下午
     */
    public void registryWatch(String rpcRoot, List<String> childrenList) {
        // 监听子节点
        zkClient.subscribeChildChanges(rpcRoot, (parentPath, currentChilds) -> {
            childrenList.clear();
            childrenList.addAll(currentChilds);
            System.out.println(parentPath + "节点的子节点改变，当前子节点为：" + currentChilds);
        });
    }

    public String getChildrenNodeData(String childPath) {
        Object data = zkClient.readData(RPC_ROOT + RPC_SPLIT + childPath);
        return (String) data;
    }

    public void deleteChildNode(String childPath) {
        String path = RPC_ROOT + RPC_SPLIT + childPath;
        zkClient.delete(path);
        System.out.println("删除节点：" + path);
    }

    /**
     * 更新节点内容
     *
     * @param childPath
     * @param time：最后一次请求时间
     */
    public void updateChildrenNodeData(String childPath, String time) {
        zkClient.writeData(RPC_ROOT + RPC_SPLIT + childPath, time);
    }
}
